package com.e1xp.deport_management_system.utils;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Ea1xP@foxmail.com
 * @version 1.0
 * @PACKAGE_NAME com.e1xp.deport_management_system.utils
 * @CLASS_NAME LocalDateConverter
 * @Description TODO 用于接收前段LocalDate的转换器
 * @Date 2021/3/21 上午 10:52
 **/
@Component
public class LocalDateConverter implements Converter<String, LocalDate> {

    static List<DateTimeFormatter> formatter = new ArrayList<>();

    static {
        formatter.add(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        formatter.add(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

    }

    @Override
    public LocalDate convert(String source) {
        if (Pattern.matches("\\d{4}-\\d{2}-\\d{2}", source)) {
            return LocalDate.parse(source, formatter.get(0));
        }
        if (Pattern.matches("\\d{4}/\\d{2}/\\d{2}", source)) {
            return LocalDate.parse(source, formatter.get(1));
        }
        return null;
    }
}
